export const initMqtt = (callback) => {
  return new Promise((resolve) => {
    fetch("https://v2.huiyidun.com/api/mqtt")
      .then((res) => res.json())
      .then((res) => {
        const utils = MQTTconnect(res.data, callback);
        resolve(utils);
      });
  });
};

// @ts-ignore
let mqtt;

function MQTTconnect(info, callback) {
  if (!mqtt) {
    mqtt = new window.Paho.MQTT.Client(info.host, info.port, info.clientId);
  }

  const reconnectTimeout = 2000;

  var options = {
    timeout: 3,
    onSuccess: () => {
      console.log("success");
      mqtt.subscribe(info.topic, { qos: 0 });
    },
    mqttVersion: 4,
    cleanSession: false,
    keepAliveInterval: 30,
    onFailure: function (message) {
      //连接失败自动重连
      console.log("onFailure", message);
      setTimeout(() => {
        MQTTconnect(info, callback);
      }, reconnectTimeout);
    },
  };
  mqtt.onConnectionLost = () => {
    console.log("lost");
    setTimeout(() => {
      MQTTconnect(info, callback);
    }, reconnectTimeout);
  };
  mqtt.onMessageArrived = (message) => {
    if (callback) {
      console.log("arrived");
      var topic = message.destinationName;
      var payload = message.payloadString;
      callback?.(topic, payload);
    }
  };

  if (info.username != null) {
    options.userName = info.username;
    options.password = info.password;
    options.useSSL = info.useTLS; //如果使用 HTTPS 加密则配置为 true
  }

  return () => {
    mqtt.disconnect();
    mqtt = null;
  };
}
